const _ = require('underscore');
const conn = require('../../../server/libs/DB/meter/conn');

async function checkThreshold(deviceNo, dataObj, thresholdObjStr) {
    let dataException = false;//数据异常标识
    let thresholdObj = JSON.parse(thresholdObjStr);//阈值对象数据类型转换
    let insertDataObj = {};//存储数据对象
    _.map(dataObj, function (data, key) {//挨个读取上报熬数据
        let dataItemKeyMax = key + 'Max';//将该数据类型的字段名结合阈值类型生成阈值标识 以便和redis中设置的阈值类型进行匹配
        let dataItemKeyMin = key + 'Min';
        if (thresholdObj[dataItemKeyMax] || thresholdObj[dataItemKeyMin]) {//判断阈值对象中是否设置了该字段的阈值
            data = parseFloat(data);//转换为float
            insertDataObj[key] = data;// 
            if (thresholdObj[dataItemKeyMax] && data > parseFloat(thresholdObj[dataItemKeyMax])) {//判断是否超出阈值
                insertDataObj[dataItemKeyMax] = parseFloat(thresholdObj[dataItemKeyMax]);
                dataException = true;
            }
            if (thresholdObj[dataItemKeyMin] && data < parseFloat(thresholdObj[dataItemKeyMin])) {
                insertDataObj[dataItemKeyMin] = parseFloat(thresholdObj[dataItemKeyMin]);
                dataException = true;
            }

        }
    });

    if (dataException === true) {
        await conn('insert into alarm_record set ? ', [{
            alarm_date: dataObj.currentTime,
            device_no: deviceNo + '-' + dataObj.meterAddr,
            alarm_type: 1,
            alarm_data_obj: JSON.stringify(insertDataObj)
        }]);
    }

}

exports.checkThreshold = checkThreshold;